package com.wyzz.hr.exportfile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import jxl.Workbook;
import jxl.format.*;
import jxl.write.*;
import jxl.write.Alignment;
import jxl.write.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Colour;
import jxl.write.VerticalAlignment;
import jxl.write.biff.RowsExceededException;

public abstract class ExportHandler {

	public ExportHandler() {
	}

	public void export(String filename) throws Exception {
		FileOutputStream fileOutputStream = new FileOutputStream(filename);
		writableWorkbook = Workbook.createWorkbook(fileOutputStream);
		WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 10,
				WritableFont.BOLD, false);
		titleCellFormat = new WritableCellFormat(titleFont);
		titleCellFormat.setBackground(Colour.GRAY_25);
		setAlignmentAndWrap(titleCellFormat);
		titleCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
		WritableFont writableFont = new WritableFont(WritableFont.ARIAL, 9,
				WritableFont.NO_BOLD, false);
		defaultCellFormat = new WritableCellFormat(writableFont);
		setAlignmentAndWrap(defaultCellFormat);
		NumberFormat nf = new NumberFormat("#0.00");
		numberCellFormat = new WritableCellFormat(nf);
		setAlignmentAndWrap(numberCellFormat);
		NumberFormat nf1 = new NumberFormat("#0.0");
		numberCellFormat1 = new WritableCellFormat(nf1);
		setAlignmentAndWrap(numberCellFormat1);
		buildTitle();
		buildBody();
		releaseResource();
		if (null != fileOutputStream) {
			fileOutputStream.close();
			fileOutputStream = null;
		}
	}

	protected abstract void buildTitle() throws RowsExceededException,
			WriteException;

	protected abstract void buildBody() throws RowsExceededException,
			WriteException, IOException;

	private void releaseResource() throws WriteException, IOException {
		if (writableWorkbook != null) {
			writableWorkbook.close();
			writableWorkbook = null;
		}
	}

	protected void setAlignmentAndWrap(WritableCellFormat cellFormat)
			throws Exception {
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setWrap(true);
	}

	protected String formatDate(Date date) {
		if (date == null) {
			return "";
		} else {
			String eqDate = SIMPLE_DATEFORMAT.format(date);
			return eqDate;
		}
	}

	protected WritableWorkbook getWritableWorkbook() {
		return writableWorkbook;
	}

	protected void setWritableWorkbook(WritableWorkbook writableWorkbook) {
		this.writableWorkbook = writableWorkbook;
	}

	protected WritableWorkbook writableWorkbook;
	protected WritableCellFormat titleCellFormat;
	protected WritableCellFormat defaultCellFormat;
	protected WritableCellFormat numberCellFormat;
	protected WritableCellFormat numberCellFormat1;
	protected static SimpleDateFormat SIMPLE_DATEFORMAT = new SimpleDateFormat(
			"yyyy-MM-dd");

}
